package com.zhijiaoyun.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhijiaoyun.common.DsConstant;
import com.zhijiaoyun.common.ResponseUtils;
import com.zhijiaoyun.common.StringUtils;
import com.zhijiaoyun.dao.ICourseDao;
import com.zhijiaoyun.dao.ICourseRecommendDao;
import com.zhijiaoyun.dao.ILessonDao;
import com.zhijiaoyun.dao.IMarkDao;
import com.zhijiaoyun.dao.ITeacherDao;
import com.zhijiaoyun.model.Comment;
import com.zhijiaoyun.model.Course;
import com.zhijiaoyun.model.CourseCategory;
import com.zhijiaoyun.model.CourseRecommend;
import com.zhijiaoyun.model.dto.CourseDto;
import com.zhijiaoyun.model.dto.PageData;
import com.zhijiaoyun.model.dto.PageList;
import com.zhijiaoyun.service.ICommentService;
import com.zhijiaoyun.service.ICourseCategoryService;
import com.zhijiaoyun.service.ICourseService;
import com.zhijiaoyun.service.ITeacherService;

/**
 * @author shisfish
 * @date 2017/6/6
 */
@Service(value = "courseService")
public class CourseServiceImpl implements ICourseService {

    @Resource
    ICourseDao courseDao;

    @Autowired
    ICourseCategoryService courseCategoryService;

    @Resource
    ILessonDao lessonDao;

    @Resource
    ICourseRecommendDao courseRecommendDao;

    @Resource
    ITeacherDao teacherDao;

    @Resource
    IMarkDao markDao;

    @Resource
    ITeacherService teacherService;

    @Autowired
    ICommentService commentService;

    @Override
    public Course getCourseByName(String name) {
        return courseDao.selectByName(name);
    }

    @Override
    public void addCourse(Course course) {
        courseDao.insert(course);
    }

    @Override
    public Course getCourseByNameNotCourseId(Long courseId, String name) {
        return courseDao.selectByNameNotCourseId(courseId, name);
    }

    @Override
    public Course getCourseByCourseId(Long courseId) {
        return courseDao.selectByPrimaryKey(courseId);
    }

    @Override
    public CourseDto getCourseDtoByCourseId(Long courseId) {
        Course course = courseDao.selectByPrimaryKey(courseId);
        CourseDto courseDto = null;
        if (course != null) {
            courseDto = course2CourseDto(course);
        }
        return courseDto;
    }

    @Override
    public void modifyCourse(Course course) {
        courseDao.updateByPrimaryKey(course);
    }

    @Override
    public PageList<Course> pageByParams(Integer pageIndex, String name, String title, Integer status, List<Long> ids) {
        int count = courseDao.countByParams(name, title, status, ids);
        PageData pageData = new PageData();
        List<Course> list = new ArrayList<>();
        PageList<Course> pageList = new PageList<>();
        if (count > 0) {
            int pageIndexInt = pageIndex == null ? 1 : pageIndex;
            pageData = PageData.createPage(count, pageIndexInt, DsConstant.PAGESIZE_DEFAULT);
            list = courseDao.pageByParams(pageData.getBeginIndex(), pageData.getPageSize(), name, title, status, ids);
            pageList = new PageList<>(list, pageData);
        }
        return pageList;
    }

    @Override
    public PageList<CourseDto> pageByParamsDto(int pageIndex, int pageSize, String name, String title, Integer status, List<Long> ids) {
        int count = courseDao.countByParams(name, title, status, ids);
        PageData pageData = new PageData();
        List<CourseDto> listD = new ArrayList<>();
        PageList<CourseDto> pageList = new PageList<>();
        if (count > 0) {
            pageData = PageData.createPage(count, pageIndex, pageSize);
            List<Course> list = courseDao.pageByParams(pageData.getBeginIndex(), pageData.getPageSize(), name, title, status, ids);


            if (StringUtils.isNotEmptyList(list)) {
                for (Course course : list) {
                    CourseDto courseDto = course2CourseDto(course);

                    listD.add(courseDto);
                }
            }
            pageList = new PageList<>(listD, pageData);
        }
        return pageList;
    }

    @Override
    public void changeLessonNum(Long courseId) {
        courseDao.changeLessonNum(courseId);
    }

    @Override
    public List<Course> getCourseByIds(List<Long> ids) {
        return courseDao.selectCourseByIds(ids);
    }

    public CourseDto course2CourseDto(Course course) {
        CourseDto courseDto = new CourseDto(course);
        // 分类中文
        String categoryNames = "";
        if (!StringUtils.isEmptyString(course.getCategoryIds())) {
            String[] categorys = course.getCategoryIds().split("/");
            for (int i = 0, len = categorys.length; i < len; i++) {
                CourseCategory courseCategory = courseCategoryService.getCourseCategoryByCategoryId(Long.parseLong(categorys[i]));
                if (courseCategory != null) {
                    categoryNames += "/" + courseCategory.getName();
                }
            }
        }
        if (categoryNames.length() > 2) {
            courseDto.setCategoryStrs(categoryNames.substring(1));
        }

        // 是否推荐
        CourseRecommend courseRecommend = courseRecommendDao.selectByCourseId(course.getCourseId());
        if (courseRecommend == null) {
            courseDto.setIsRecommend(false);
        } else {
            courseDto.setIsRecommend(true);
        }

        // TODO 暂时不开放
//		if (!StringUtils.isEmptyString(course.getTeacherIds())) {
//			List<String> teacherIds = Arrays.asList(course.getTeacherIds().split(","));
//			List<Teacher> teachers = teacherService.listByIds(teacherIds);
//			courseDto.setTeachers(teachers);
//		}

        // TODO 暂时不开放
        // 标签中文
        String marksStrs = "";
//        if (!CommonUtils.isEmptyString(course.getMarks())) {
//            String[] marks = course.getMarks().split(",");
//            for (String string : marks) {
//                String markName = markDao.selectNameByMarkId(CommonUtils.parseLong(string, 0));
//                if (!CommonUtils.isEmptyString(markName)) {
//                    marksStrs += "，" + markName;
//                }
//            }
//        }

        if (marksStrs.length() > 2) {
            courseDto.setMarksStrs(marksStrs);
        }
        return courseDto;
    }

    @Override
    public List<CourseDto> getCourseByCategoryIds(List<Long> parentIds, int pageSize) {
        List<CourseDto> listD = new ArrayList<>();
        List<Course> list = courseDao.pageByParams(0, pageSize, null, null, -1, parentIds);
        if (!StringUtils.isEmptyList(list)) {
            for (Course course : list) {
                CourseDto courseDto = course2CourseDto(course);

                listD.add(courseDto);
            }
        }
        return listD;
    }

    @Override
    public void addSaleNum(Long courseId) {
        courseDao.addSaleNum(courseId);
    }

    @Override
    public void addViewNum(Long courseId) {
        courseDao.addViewNum(courseId);
    }

    @Override
    public void deleteCourse(Course course) {
        courseDao.deleteByPrimaryKey(course.getCourseId());

        // 把推荐也删除了
        courseRecommendDao.deleteByCourseId(course.getCourseId());
    }

    @Override
    public int countAll() {
        return courseDao.countAll();
    }

    @Override
    public Map<String, Object> getById(long courseId) {
        CourseDto courseDto = getCourseDtoBlobsByCourseId(courseId);
        Map<String, Object> map = new HashMap<>();
        map.put("obj", courseDto);
        return ResponseUtils.responseSuccessMap(map);
    }

    @Override
    public CourseDto getCourseDtoBlobsByCourseId(Long courseId) {
        Course course = courseDao.selectByPrimaryKeyBlobs(courseId);
        CourseDto courseDto = null;
        if (course != null) {
            courseDto = course2CourseDto(course);
        }
        return courseDto;
    }

    @Override
    public Map<String, Object> pageCourseHistoryByParams(int pageIndex, int pageSize, long userId, Long categorySuper, String name) {
        List<Long> ids = new ArrayList<>();
        if (categorySuper != null) {
            ids = courseCategoryService.getIdsByParentId(categorySuper);
        }
        int count = courseDao.countCourseHistoryByParams(userId, name, ids);
        PageList<CourseDto> pageList = new PageList<>();
        if (count > 0) {
            PageData pageData = PageData.createPage(count, pageIndex, pageSize);
            List<Course> list = courseDao.pageCourseHistoryByParams(pageData.getBeginIndex(), pageData.getPageSize(), userId, name, ids);
            List<CourseDto> dtoList = new ArrayList<>();
            if (StringUtils.isNotEmptyList(list)) {
                for (Course course : list) {
                    dtoList.add(course2CourseDto(course));
                }
            }
            pageList = new PageList<>(dtoList, pageData);
        }
        Map<String, Object> map = new HashMap<>();
        map.put(ResponseUtils.PAGE, pageList.getPageData());
        map.put(ResponseUtils.LIST, pageList.getList());
        return ResponseUtils.responseSuccessMap(map);
    }

    @Override
    public Map<String, Object> comment(long courseId, String message, long userId) {
        Course course = getCourseByCourseId(courseId);
        if (course == null) {
            return ResponseUtils.responseCourseLost();
        }
        Comment comment = new Comment(courseId, userId, message);
        commentService.insert(comment);
        return ResponseUtils.responseSuccessMap();
    }

    @Override
    public Map<String, Object> deleteComment(long id, long userId) {
        Comment comment = commentService.getById(id);
        if (comment == null) {
            return ResponseUtils.responseCourseLost();
        }
        if (comment.getUserId().longValue() != userId) {
            return ResponseUtils.responseCourseLost();
        }
        commentService.delete(comment);
        return ResponseUtils.responseSuccessMap();
    }

    @Override
    public Map<String, Object> listComments(int pageIndex, int pageSize, long courseId) {
        Course course = getCourseByCourseId(courseId);
        if (course == null) {
            return ResponseUtils.responseCourseLost();
        }
        PageList<Comment> pageList = commentService.pageByCourseId(pageIndex, pageSize, courseId);
        Map<String, Object> map = new HashMap<>();
        map.put(ResponseUtils.LIST, pageList.getList());
        map.put(ResponseUtils.PAGE, pageList.getPageData());
        return ResponseUtils.responseSuccessMap(map);
    }

    @Override
    public Map<String, Object> pageByParamsDto(int pageIndex, int pageSize, String name, String title, Integer status, Long category1, Long category2) {

        List<Long> ids = new ArrayList<>();
        if (category1 != null && category2 != null) {
            if (category2 == -1) {
                if (category1 != -1) {
                    ids = courseCategoryService.getIdsByParentId(category1);
                }
             } else {
                ids.add(category2);
            }
        }

        PageList<CourseDto> courses = pageByParamsDto(pageIndex, pageSize, name, title,
                status == null ? -1 : status, ids);
        Map<String, Object> map = new HashMap<>();
        map.put(ResponseUtils.LIST, courses.getList());
        map.put(ResponseUtils.PAGE, courses.getPageData());

        return ResponseUtils.responseSuccessMap(map);
    }

}
